package core;

import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Random;
import java.util.concurrent.Semaphore;

/**
 * implementa o filosofo
 * @author jjeske
 *
 */
public class Philosoper implements Runnable{
	
	private Semaphore[] sem;
	private int id;	
	private Random rand;
	//private Helper helper;
	private Thread helper = new Thread();
	
	public Philosoper(Semaphore[] sem, int id) {
		this.sem = sem;
		this.id = id;
		this.helper =  new Thread(new Helper(this.id, ((this.id + 1) % 5)));
		this.helper.start();		
	}

	@Override
	public void run() {
		rand = new Random();
		
		System.out.println("teste, liberando todos os garfos com o helper");
		vop(this.id, this.id);
				
		while(true){
			try {
				sem[this.id].acquire();
				System.out.println("Philosoper_" + this.id + "has right fork");
				//pensa(); //Isso aqui causa um Abraço Mortal !
				sem[(this.id + 1) % 5].acquire();
				System.out.println("Philosoper_" + this.id + "has left fork");
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			System.out.println("Philosoper_" + this.id + "is Eating");
			sem[this.id].release();
			pensa();
			sem[(this.id + 1) % 5].release();
			System.out.println("Philosoper_" + this.id + "is thinkig");
			pensa();
		}		
	}	
	/**
	 * para randomicamente entre 0 e 5 sgundos
	 */
	private void pensa(){
		try {
			Thread.sleep(rand.nextInt(5)*1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}		
	}
	
	/**
	 * envia uma mensagem de VOP para todos e aguarda um retorno confirmado
	 * VOP = liberar o garfo
	 * @param numeroGarfo
	 */
	public void vop(int numeroGarfo, int idFilosofo){
		
		for(int i=0;i<5;i++){ //broadcast
			if(i != idFilosofo){
				Socket clientSocket;
				try {
					clientSocket = new Socket("localhost",6789);
					//DataInputStream in = new DataInputStream(clientSocket.getInputStream());
					DataOutputStream out = new DataOutputStream(clientSocket.getOutputStream());
					out.writeInt(idFilosofo);
					out.writeInt(i); //fazer broadcast !
					out.writeInt(numeroGarfo);
					out.writeInt(3);
					out.close();
					clientSocket.close();	
				} catch (UnknownHostException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}			
			}
		}
		
		//return true;
	}	
	
	
	

}
